package com.wdl.webserver;

import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableCaching
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
public class SecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter  {
    private static final Logger LOG = LoggerFactory.getLogger("SecurityConfiguration");

    @Value("${webserver.backend-security-enabled:true}")
    boolean backendSecurityEnabled;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);

        if (backendSecurityEnabled) {
            LOG.info("==========+++++ BACKEND SECURITY IS ENABLED +++++========");
            // Predefined roles: superAdmin, superOperator, admin, operator, viewer
            http.cors().and().authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers("/api/keycloak/validate/**").permitAll()
                .antMatchers("/api/sms/wdlCodeWxshtuiuykdkdkdppwee").permitAll()
                .antMatchers("/api/keycloak/register").permitAll()
                .antMatchers("/api/keycloak/forget-password").permitAll()
                .antMatchers("/api/su/**").access("hasAnyRole('header')")
                .antMatchers("/api/**").access("hasAnyRole('super', 'admin', 'director', 'header', 'doctor', 'nurse', 'family', 'user')")
                .antMatchers("/data/**").access("hasAnyRole('super', 'admin', 'director', 'header', 'doctor', 'nurse', 'family', 'user')")
//              .antMatchers(HttpMethod.GET, "/api/keycloak/*").access("hasAnyRole('superAdmin', 'superOperator', 'admin', 'operator', 'viewer')")
//              .antMatchers("/api/*").access("hasRole('trainee') or hasRole('operator')")
                .anyRequest().permitAll()
                .and().csrf().disable();
        } else {
            LOG.info("==========+++++ BACKEND SECURITY IS DISABLED +++++========");
            http.cors().and().authorizeRequests()
                .anyRequest().permitAll()
                .and().csrf().disable();
        }
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();

        // SimpleAuthorityMapper is used to remove prefix ROLE_ for user role mapping
        keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());

        auth.authenticationProvider(keycloakAuthenticationProvider);
    }

    @Bean
    public KeycloakSpringBootConfigResolver KeycloakConfigResolver() {
        // to use spring boot properties to replace keycloak.json
        return new KeycloakSpringBootConfigResolver();
    }

    // Specifies the session authentication strategy
    @Bean
    @Override
    protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
        return new NullAuthenticatedSessionStrategy();
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}